<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/12
 * Time: 16:03
 */

namespace common\business;

use common\business\qywx\QywxAccessTokenApiHandler;
use common\consts\CommonResources;
use common\models\qywx\QywxDepartment;
use common\result\ActionResult;
use Yii;
use common\consts\Consts;
use common\helpers\DateHelper;
use common\helpers\StringUtil;
use common\models\Log;
use common\models\qywx\QywxAccessToken;
use common\models\qywx\QywxApp;
use common\models\qywx\QywxUser;
use yii\helpers\Json;

/**
 * Class QywxHelper
 * @package common\business
 */
class QywxHelper
{
    /**
     * @var QywxAccessToken
     */
    protected static $active_access_token;

    /**
     * @var QywxApp
     */
    protected static $qywx_app;


    /**
     * 得到ehr应用的
     * @return QywxApp
     */
    protected static function getApp(){
        if (self::$qywx_app){
            return self::$qywx_app;
        }

        $app = QywxApp::findOne([
           'qywx_app_name' => 'ehr',
        ]);

        self::$qywx_app = $app;
        return self::$qywx_app;
    }

    /**
     * @return QywxAccessToken
     */
    protected static function getExistedAccessToken(){
        if (self::$active_access_token && !StringUtil::isNullOrWhiteSpace(self::$active_access_token->created_at)) {
            //为了保险起见，少算10秒的生效时间
            $expireTime = DateHelper::calFormatDateTimeWithSeconds(self::$active_access_token->created_at, self::$active_access_token->expires_in - 10);
            date_default_timezone_set('PRC'); //设置为东八区时间
            //如果没过期
            if (time() <= strtotime($expireTime)) {
                return self::$active_access_token;
            }
            //否则过期了，更新$active_access_token状态并且删除之
            self::$active_access_token->status = Consts::ACCESS_TOKEN_STATUS_INACTIVE;
            self::$active_access_token->save();
            self::$active_access_token = null;
        }

        $existed_access_token = QywxAccessToken::findOne([
           'status' => Consts::ACCESS_TOKEN_STATUS_ACTIVE
        ]);

        if (!$existed_access_token) return null;
//为了保险起见，少算10秒的生效时间
        $expireTime = DateHelper::calFormatDateTimeWithSeconds($existed_access_token->created_at, $existed_access_token->expires_in - 10);
//        如果当前时间超过了token的创建时间加上token的生效时间
        date_default_timezone_set('PRC'); //设置为东八区时间
        if (time() > strtotime($expireTime)) {
//            token已经过期了
            $existed_access_token->status = Consts::ACCESS_TOKEN_STATUS_INACTIVE;
            $existed_access_token->save();
            return null;
        }

        self::$active_access_token = $existed_access_token;
        return self::$active_access_token;
    }

    /**
     * @param QywxApp|null $app
     * @return QywxAccessToken
     */
    public static function getAccessToken(QywxApp $app = null){
        $existed = self::getExistedAccessToken();
        if ($existed) return $existed;

        if ($app == null){
            $app = self::getApp();
        }

        $api = new QywxAccessTokenApiHandler();
        $writeBackHandler = function($errcode, $errmsg, $access_token, $expires_in) use ($app, $api) {
            $newAccessToken = new QywxAccessToken([
                'app_id' => $app->qywx_app_id,
                'val' => $access_token,
                'expires_in' => $expires_in,
                'errcode' => strval($errcode),
                'errmsg' => $errmsg,
                'status' => Consts::ACCESS_TOKEN_STATUS_ACTIVE,
            ]);
            $api->createQywxAccessToken($newAccessToken);
            self::$active_access_token = $newAccessToken;
        };
        $api->createOnQywx($app->qywx_app_corp_id, $app->qywx_app_corp_secret, $writeBackHandler);
        return self::$active_access_token;
    }

    /**
     * @return string
     */
    public static function getAccessTokenVal(){
        if (self::getAccessToken() == null)
            return null;
        return self::getAccessToken()->val;
    }

    /**
     * @param $departmentInDb QywxDepartment
     * @param $departmentArr array
     {
    "errcode": 0,
    "errmsg": "ok",
    "department": [
    {
    "id": 2,
    "name": "广州研发中心",
    "parentid": 1,
    "order": 10
    },
    {
    "id": 3
    "name": "邮箱产品部",
    "parentid": 2,
    "order": 40
    }
    ]
    }
     * @return ActionResult
     */
    public static function syncSingleQywxDepartmentByArr($departmentInDb, $departmentArr){
        $action = Yii::t('app' , 'Update');
        $modelClass = Yii::t('app' , 'Department');

        $newDepartment = new QywxDepartment([
            'qywx_department_wx_id' => $departmentArr['id'],
            'qywx_department_name' => $departmentArr['name'],
            'qywx_department_parent_wx_id' => $departmentArr['parentid'],
            'qywx_department_order' => $departmentArr['order'],
        ]);
        $compareResult = CommonHelper::compareObjectAttributes($departmentInDb, $newDepartment, [
            'qywx_department_wx_id',
            'qywx_department_name',
            'qywx_department_parent_wx_id',
            'qywx_department_order',
        ]);
        if (!$compareResult->isChanged){
            return new ActionResult(true, Yii::t('app',  CommonResources::OBJECT_NOT_CHANGED($modelClass)), true);
        }

        $updateLog = new Log([
            'action' => CommonResources::ACTION_MSG($action, $modelClass),
            'memo' => $compareResult->message,
        ]);
        $departmentInDb->setAttributes($newDepartment->getAttributes());
        $dbHandler = new DbHandler();
        $isSuccess = $dbHandler->saveRecordWithLogUnsafe($departmentInDb, $updateLog);
        if ($isSuccess){
            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        }
        else {
            return new ActionResult(false, $dbHandler->getErrorsMessage());
        }
    }


    /**
     * @param $userInDb QywxUser
     * @param $userArr array
     * {
    "userid": "zhangsan",
    "name": "李四",
    "department": [1, 2],
    "order": [1, 2],
    "position": "后台工程师",
    "mobile": "15913215421",
    "gender": "1",
    "email": "zhangsan@gzdev.com",
    "isleader": 0,
    "avatar":           "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0",
    "telephone": "020-123456",
    "english_name": "jackzhang",
    "status": 1,
    "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
    }
     * @return ActionResult
     */
    public static function syncSingleQywxUserByArr($userInDb, $userArr){
        $action = Yii::t('app' , 'Update');
        $modelClass = Yii::t('app' , 'User');

        $newUser = QywxHelper::arrayToQywxUser($userArr);
        $compareResult = CommonHelper::compareObjectAttributes($userInDb, $newUser, [
            'qywx_user_name',
            'qywx_user_department',
            'qywx_user_order',
            'qywx_user_position',
            'qywx_user_mobile',
            'qywx_user_gender',
            'qywx_user_email',
            'qywx_user_isleader',
            'qywx_user_avatar',
            'qywx_user_telephone',
            'qywx_user_english_name',
            'qywx_user_status',
            'qywx_user_extattr',
        ]);
        if (!$compareResult->isChanged){
            return new ActionResult(true, Yii::t('app',  CommonResources::$OBJECT_NOT_CHANGED), true);
        }

        try {
            $newLog = new Log([
                'action' => CommonResources::ACTION_MSG($action, $modelClass),
                'memo' => $compareResult->message,
            ]);

            $userInDb->setAttributes($newUser->getAttributes());
            CommonHelper::persistRecordWithLog($userInDb, $newLog);
            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        } catch (\Exception $e) {
            return new ActionResult(false, $e->getMessage(), false, $e);
        }
    }


    /**
     * @param $userArr
     * {
    "userid": "zhangsan",
    "name": "李四",
    "department": [1, 2],
    "order": [1, 2],
    "position": "后台工程师",
    "mobile": "15913215421",
    "gender": "1",
    "email": "zhangsan@gzdev.com",
    "isleader": 0,
    "avatar":           "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0",
    "telephone": "020-123456",
    "english_name": "jackzhang",
    "status": 1,
    "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
    }
     * @return QywxUser
     */
    public static function arrayToQywxUser($userArr){
        $newUser = new QywxUser([
            'qywx_user_userid' => $userArr['userid'],
            'qywx_user_name' => $userArr['name'],
            'qywx_user_department' => Json::encode($userArr['department']),
            'qywx_user_order' => Json::encode($userArr['order']),
            'qywx_user_position' => $userArr['position'],
            'qywx_user_mobile' => $userArr['mobile'],
            'qywx_user_gender' => $userArr['gender'],
            'qywx_user_email' => $userArr['email'],
            'qywx_user_isleader' => $userArr['isleader'],
            'qywx_user_avatar' => $userArr['avatar'],
            'qywx_user_telephone' => $userArr['telephone'],
            'qywx_user_english_name' => $userArr['english_name'],
            'qywx_user_status' => $userArr['status'],
            'qywx_user_extattr' => Json::encode($userArr['extattr']),
        ]);
        return $newUser;
    }


    /**
     * @param $departmentArr
    {
    "id": 2,
    "name": "广州研发中心",
    "parentid": 1,
    "order": 1
    }
     * @return QywxDepartment
     */
    public static function arrayToQywxDepartment($departmentArr){
        $newDepartment = new QywxDepartment([
            'qywx_department_wx_id' => $departmentArr['id'],
            'qywx_department_name' => $departmentArr['name'],
            'qywx_department_parent_wx_id' => $departmentArr['parentid'],
            'qywx_department_order' => $departmentArr['order'],
        ]);
        return $newDepartment;
    }


    /**
     * @param $userArr
     * {
    "userid": "zhangsan",
    "name": "李四",
    "department": [1, 2],
    "order": [1, 2],
    "position": "后台工程师",
    "mobile": "15913215421",
    "gender": "1",
    "email": "zhangsan@gzdev.com",
    "isleader": 0,
    "avatar":           "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3WJ6DSZUfiakYe37PKnQhBIeOQBO4czqrnZDS79FH5Wm5m4X69TBicnHFlhiafvDwklOpZeXYQQ2icg/0",
    "telephone": "020-123456",
    "english_name": "jackzhang",
    "status": 1,
    "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
    }
     * @return ActionResult
     */
    public static function newQywxUserByArr($userArr){
        $action = Yii::t('app' , 'Create');
        $modelClass = Yii::t('app' , 'User');

        try {
            $newUser = self::arrayToQywxUser($userArr);
            $forPrintContent = [
                'userid' => $newUser->qywx_user_userid,
                'name' => $newUser->qywx_user_name,
                'department' => $newUser->qywx_user_department,
                'order' => $newUser->qywx_user_order,
                'position' => $newUser->qywx_user_position,
                'mobile' => $newUser->qywx_user_mobile,
                'gender' => $newUser->qywx_user_gender,
                'email' => $newUser->qywx_user_email,
                'isleader' => $newUser->qywx_user_isleader,
                'avatar' => $newUser->qywx_user_avatar,
                'telephone' => $newUser->qywx_user_telephone,
                'english_name' => $newUser->qywx_user_english_name,
                'status' => $newUser->qywx_user_status,
                'extattr' => $newUser->qywx_user_extattr,
            ];
            $newLog = new Log([
                'action' => CommonResources::ACTION_MSG($action, $modelClass),
                'old_content' => '-',
                'new_content' => Json::encode($forPrintContent),
            ]);
            CommonHelper::persistRecordWithLog($newUser, $newLog);
            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        } catch (\Exception $e) {
            return new ActionResult(false, $e->getMessage(), false, $e);
        }
    }


    /**
     * @param $departmentArr
    {
    "id": 2,
    "name": "广州研发中心",
    "parentid": 1,
    "order": 1
    }
     * @return ActionResult
     */
    public static function newQywxDepartmentByArr($departmentArr){
        $action = Yii::t('app' , 'Create');
        $modelClass = Yii::t('app' , 'Department');

        $newDepartment = QywxHelper::arrayToQywxDepartment($departmentArr);
        $forPrintContent = [
            'qywx_id' => $newDepartment->qywx_department_wx_id,
            'name' => $newDepartment->qywx_department_name,
            'parent_qywx_id' => $newDepartment->qywx_department_parent_wx_id,
            'order' => $newDepartment->qywx_department_order,
        ];
        $newLog = new Log([
            'action' => CommonResources::ACTION_MSG($action, $modelClass),
            'old_content' => '-',
            'new_content' => Json::encode($forPrintContent),
        ]);

        $dbHandler = new DbHandler();
        $isSuccess = $dbHandler->saveRecordWithLogUnsafe($newDepartment, $newLog);
        if ($isSuccess){
            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        }
        else {
            return new ActionResult(false, $dbHandler->getErrorsMessage());
        }
    }
}